<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-02-24
 * Time: 12:15
 */

namespace app\mall\service;

use app\model\CompanyAdmin;
use app\model\Coupon;
use app\model\MyCoupon;

class AdminService extends BaseService{

    function lists($company_id, $pageSize)
    {
        $data = CompanyAdmin::alias('a')
            ->join('customer c', 'a.customer_id = c.id')
            ->where([
            'a.company_id'=> $company_id
            ])->field('c.nickname, c.avatar_url, c.id')->order('a.id desc')->paginate($pageSize);

        return $data;
    }

    function addAdmin($data)
    {
        $count = CompanyAdmin::where($data)->count();
        if(!$count)
        {
            CompanyAdmin::insert($data);
        }
    }

    function deleteAdmin($where)
    {
        CompanyAdmin::where($where)->delete();
    }

    function couponList($company_id, $pageSize)
    {
        $where = [
            'uid'=> $company_id
        ];
        $data = Coupon::where($where)->field('create_time, coupon_id, name, start_time, expired_date, type, description, address, supermarket, value, code_url, condition, num, expired_type')->order('coupon_id desc')->paginate($pageSize)->each(function (&$item){
            $count = MyCoupon::where(['coupon_id'=> $item['coupon_id']])->field('count(id) as num, status')->group('status')->select();
            $count = collection($count)->toArray();
            $count = array_column($count, 'num', 'status');
            $item['fa'] = array_sum($count);
            $item['he'] = $count['2']?:0;
            if($item['expired_type'] == 1)
            {
                $item['end_time'] = date('Y-m-d', strtotime($item['start_time']) + 86400*$item['expired_date']);
            }else{
                $item['start_time'] = 0;
                $item['end_time'] = 0;
            }
            return $item;
        });
        return $data;

    }

    function member($where, $pageSize)
    {
        $where['m.is_new'] = 1;
        $data = db('master_log m')
            ->join('customer c', 'c.id = m.u_id')
            ->where($where)
            ->field('c.avatar_url, c.nickname, m.create_time')
            ->order('m.id desc')
            ->paginate($pageSize);

        $where['m.create_time'] = date('Y-m-d');
        $count = db('master_log m')
            ->where($where)
            ->count();

        return [
            'list'=> $data,
            'day_count'=> $count
        ];
    }
}